package com.share.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.share.api.order.api.RemoteOrderInfoService;
import com.share.api.order.domain.OrderInfo;
import com.share.common.core.domain.R;
import com.share.payment.domian.PaymentInfo;
import com.share.payment.mapper.PaymentInfoMapper;
import com.share.payment.service.IPaymentInfoService;

import com.share.rabbit.constant.MqConst;
import com.share.rabbit.service.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {


    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Autowired
    RabbitService rabbitService;



    /**
     * 保存支付信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //根据订单编号查询支付记录
        PaymentInfo paymentInfo =
                baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo));

        //2 如果支付记录不存在，进行添加
        if (paymentInfo == null){
            //3 远程调用：根据订单编号查询订单数据
            R<OrderInfo> result = remoteOrderInfoService.getByOrderNo(orderNo);
            OrderInfo orderInfo = result.getData();

            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setContent("共享充电宝租借");
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(0);
            baseMapper.insert(paymentInfo);


        }
        return paymentInfo;
    }


//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void updatePaymentStatus(Transaction transaction) {
//        //1 更新支付记录状态：已经支付
//        String outTradeNo = transaction.getOutTradeNo();
//        //根据订单编号查询支付记录
//        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
//                .eq(PaymentInfo::getOrderNo, outTradeNo));
//
//        //判断如果支付记录状态已经修改了，不需要操作
//        Integer paymentStatus = paymentInfo.getPaymentStatus();
//        if (paymentStatus.intValue() == 1){
//            return;
//        }
//
//        //没有修改，再进行修改
//        paymentInfo.setPaymentStatus(1);
//        paymentInfo.setOrderNo(transaction.getOutTradeNo());
//        paymentInfo.setTransactionId(transaction.getTransactionId());
//        paymentInfo.setCallbackTime(new Date());
//        paymentInfo.setCallbackContent(com.alibaba.fastjson.JSON.toJSONString(transaction));
//        this.updateById(paymentInfo);
//
//        //2 基于MQ通知订单系统，修改订单状态
//        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY,
//                                  MqConst.ROUTING_PAYMENT_PAY,
//                                  paymentInfo.getOrderNo());
//    }


    /**
     * 支付状态查询
     * @param orderNo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePaymentStatus(String orderNo) {
        //1 更新支付记录状态：已经支付
        //根据订单编号查询支付记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));

        //判断如果支付记录状态已经修改了，不需要操作
        Integer paymentStatus = paymentInfo.getPaymentStatus();
        if (paymentStatus.intValue() == 1){
            return;
        }

        //没有修改，再进行修改
        paymentInfo.setPaymentStatus(1);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setTransactionId(generateTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent("支付成功");
        this.updateById(paymentInfo);

        //2 基于MQ通知订单系统，修改订单状态
        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY,
                MqConst.ROUTING_PAYMENT_PAY,
                paymentInfo.getOrderNo());
    }

    //生成随机交易编号
    public static String generateTransactionId() {
        // 获取当前时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());

        // 生成随机数
        Random random = new Random();
        int randomNum = random.nextInt(900000) + 100000;

        // 组合成交易编号
        return "WX" + timestamp + randomNum;
    }
}